/*
 * @Author: Wangjun
 * @Date: 2021-05-15 22:46:26
 * @LastEditTime: 2023-04-18 10:56:45
 * @LastEditors: Wangjun
 * @Description:
 * @FilePath: \lua\luadb\luacmd\main.go
 * hnxr
 */
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"time"

	"gitee.com/haodreams/golib/env"
	"gitee.com/haodreams/golib/logs"
	"gitee.com/haodreams/lua/luadb"
	"gitee.com/haodreams/lua/luastring"
	lua "github.com/yuin/gopher-lua"
	"gorm.io/driver/mysql"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

func main() {
	// if len(os.Args) < 2 {
	// 	fmt.Println("Usage:", os.Args[0], "xx.lua")
	// 	return
	// }
	env.Reset()
	loadDBs()
	l := lua.NewState()
	luastring.InitLuaString(l)
	luadb.InitLuaDB(l)
	//models.InitLua(l)
	err := l.DoFile("xx.lua")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
}

func loadDBs() {
	file, err := os.Open("dbs.csv")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer file.Close()
	buf := bufio.NewReader(file)
	idx := 0
	for line, err := buf.ReadString('\n'); err == nil || len(line) > 0; line, err = buf.ReadString('\n') {
		idx++
		line = strings.TrimSpace(line)
		if line == "" {
			continue
		}
		ss := strings.Split(line, ",")
		if len(ss) < 3 {
			fmt.Println("Error: Line=", idx, line)
			continue
		}
		for i := range ss {
			ss[i] = strings.TrimSpace(ss[i])
		}

		var db *gorm.DB
		switch ss[0] {
		case "sqlite3":
			db, err = gorm.Open(sqlite.Open(ss[1]), &gorm.Config{
				NamingStrategy: schema.NamingStrategy{
					SingularTable: true,
				},
			})
		case "mysql":
			db, err = gorm.Open(mysql.Open(ss[1]), &gorm.Config{
				NamingStrategy: schema.NamingStrategy{
					SingularTable: true,
				},
			})
		case "opdb":
			db, err = gorm.Open(sqlite.Open("data/data.db"), &gorm.Config{
				NamingStrategy: schema.NamingStrategy{
					SingularTable: true,
				},
			})
		default:
			logs.Error("不支持的驱动", ss[1])
			continue
		}
		if err != nil {
			logs.Error(err)
			continue
		}
		gdb, err := db.DB()
		if err != nil {
			logs.Error("db 错误", ss[1])
			continue
		}
		gdb.SetConnMaxLifetime(time.Second * 1800)
	}
}
